// Copyright 2011 The OnTheQuarter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package server

import (
	"appengine"
	"appengine/datastore"
	"fmt"
	"json"
	"http"
	"log"
)

func init() {
	http.HandleFunc("/save", save)
}

func save(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	if r.Method != "POST" {
		http.Error(w, "expected POST", http.StatusInternalServerError)
		return
	}

	var body struct {
		Shortname string
		Quarter Quarter
		Objective []Objective
	}
	err := json.NewDecoder(r.Body).Decode(&body)
	if err != nil {
		e := fmt.Sprintf("bad body read: %s", err)
		log.Printf(e)
		http.Error(w, e, http.StatusInternalServerError)
		return
	}

	if !body.Quarter.valid() {
		e := fmt.Sprintf("bad quarter: %s", body.Quarter)
		http.Error(w, e, http.StatusInternalServerError)
		return
	}

	pkey := datastore.NewKey(c, "OTQ", body.Shortname, 0, nil)
	qkey := datastore.NewKey(c, "OTQ", string(body.Quarter), 0, pkey)

	okrs := packOKRs(body.Objective)
	if _, err = datastore.Put(c, qkey, okrs); err != nil {
		e := fmt.Sprintf("bad put: %s", err)
		http.Error(w, e, http.StatusInternalServerError)
		return
	}

	log.Printf("got: %v", body)
	fmt.Fprintf(w, "{ \"success\": 1 }\n")
}
